package com.yycx.module.bus.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.bpm.provider.common.CommentTypeEnum;
import com.yycx.bpm.provider.service.ProcessInstanceService;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaDelete;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.*;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseRoleService;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.BusBankStatement;
import com.yycx.module.bus.client.entity.hy.BusHyorderInovice;
import com.yycx.module.bus.client.entity.hy.BusPolicyDrug;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.client.enums.DeptTypeEnum;
import com.yycx.module.bus.client.vo.HyBankItem;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.mapper.BusPaymentMapper;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.*;
import com.yycx.module.file.provider.service.SysFileService;
import com.yycx.module.system.client.entity.SysBank;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.provider.service.SysBankService;
import com.yycx.module.system.provider.service.SysCompanyService;
import org.flowable.engine.TaskService;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 付款单接口实现类
 *
 * @author flyme
 * @date 2020-09-07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusPaymentServiceImpl extends BaseServiceImpl<BusPaymentMapper, BusPayment> implements BusPaymentService {


    @Autowired
    private OrderNoUtil orderNoUtil;
    @Autowired
    private BusinessUtils businessUtils;
    @Autowired
    private BusDeptService deptService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private BaseUserService userService;
    @Autowired
    private BusSupplierService supplierService;
    @Autowired
    private BusSupplierBankService supplierBankService;
    @Autowired
    private BusInvoiceunitService invoiceunitService;
    @Autowired
    private BusSalemanService salemanService;
    @Autowired
    private BusSalemanBankService salemanBankService;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private BaseRoleService roleService;
    @Autowired
    private BusPaymenttypeService paymenttypeService;
    @Autowired
    private BusInvoiceunitBankService invoiceunitBankService;
    @Autowired
    private BusOrderDetailsService orderDetailsService;

    @Autowired
    private BusHyorderReturnService hyorderReturnService;
    @Autowired
    private BusOrderService orderService;
    @Autowired
    private BusConsumptionService consumptionService;
    @Autowired
    private SysCompanyService companyService;
    @Autowired
    private SysBankService bankService;
    @Autowired
    private BusDrugsService drugsService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private BusCustomService busCustomService;
    @Autowired
    private HyOrderDetailService hyOrderDetailService;
    @Autowired
    private BusPolicyDrugService policyDrugService;
    @Autowired
    private BusCustomBalanceService customBalanceService;
    @Autowired
    private BusCustomBankService customBankService;

    @Autowired
    private BusBankStatementService bankStatementService;

    @Autowired
    private BusHyorderInoviceDetailsService orderInoviceDetailsService;

    @Autowired
    private BusHyorderInoviceService hyorderInoviceService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusPayment payment, EntityMap extra) {
        payment.setPrintTag(CommonConstants.DISABLED);
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusPayment> cq, BusPayment payment, EntityMap requestMap) {

        return ResultBody.ok();
    }


    @Override
    public BusPayment getByOrderIdAndAmountType(Serializable orderId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "orderId", orderId);
        cq.eq(true, "amountType", amountType.getCode());
        return getOne(cq, false);
    }


    @Override
    public BusPayment getByParentIdAndAmountType(Serializable parentId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "parentId", parentId);
        cq.eq(true, "amountType", amountType.getCode());
        return getOne(cq, false);
    }


    @Override
    public List<BusPayment> selectByOrderIdAndAmountType(Serializable orderId, AmountTypeEnum amountType, Integer paymentState) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        if (FlymeUtils.isNotEmpty(orderId)) {
            cq.eq(true, "orderId", orderId);
        }
        cq.eq(true, "paymentState", paymentState);
        cq.eq(true, "amountType", amountType.getCode());
        cq.gt("surplusAmount", 0);
        cq.orderByAsc("amount");
        return list(cq);
    }

    @Override
    public List<BusPayment> selectByOrderIdAndAmountType(Serializable orderId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "orderId", orderId);
        cq.eq(true, "amountType", amountType.getCode());
        return list(cq);
    }

    @Override
    public BusPayment getByOrderIdAndAmountType(Serializable orderId, Long bankId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "orderId", orderId);
        cq.eq(true, "bankId", bankId);
        cq.eq(true, "amountType", amountType.getCode());
        return getOne(cq, false);
    }

    @Override
    public BusPayment getByPaymentIdAndAmountType(Long paymentId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "paymentId", paymentId);
        cq.eq(true, "amountType", amountType.getCode());
        return getOne(cq, false);
    }


    @Override
    public ResultBody initSettlePayment(Long orderDetailsId) {
        BusOrderDetails orderDetails = orderDetailsService.getById(orderDetailsId);
        BusOrderDetails parent = orderDetailsService.getById(orderDetails.getParentId());
        if (FlymeUtils.isNotEmpty(parent)) {
            BusPayment payment = getByPaymentIdAndAmountType(orderDetails.getOrderDetailsId(), AmountTypeEnum.Settle);
            if (FlymeUtils.isEmpty(payment)) {
                BusOrder order = orderService.getById(orderDetails.getOrderId());
                payment = new BusPayment();
                payment.setPaymentNo("JS" + order.getOrderNo().substring(1));
                payment.setOrderDetailsId(orderDetailsId.toString());
                payment.setOrderId(order.getOrderId().toString());
                payment.setAmount(orderDetails.getSettleAmount());
                payment.setDeptId(orderDetails.getDeptId());
                payment.setPaymentState(2);
                payment.setSupplierId(orderDetails.getSupplierId());
                payment.setCustomId(orderDetails.getCustomId().toString());
                payment.setOrganizationId(orderDetails.getOrganizationId());
                payment.setTitle("结算销售费用");
                payment.setAmountType(AmountTypeEnum.Settle.getCode());
                payment.setCompanyId(orderDetails.getCompanyId());
                save(payment);
            }
        }
        return ResultBody.ok();
    }

    @Override
    public List<EntityMap> getByOrderId(Serializable orderId) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.select(BusPayment.class, "*");
        cq.addSelect(BusSalemanBank.class, "bankName", "bankNo");
        cq.addSelect("saleman.saleManName");
        cq.eq(true, "payment.orderId", orderId);
        cq.in("amountType", AmountTypeEnum.Settle.getCode(), AmountTypeEnum.CbReturn.getCode());
        cq.createJoin(BusSalemanBank.class);
        //通过收款人账户查询收款人姓名
        cq.createJoin(BusSaleman.class).setMainAlias("bsb").setMainField("saleManId").setJoinField("saleManId");
        return selectEntityMap(cq);
    }

    @Override
    public BigDecimal totalSettleAmount(Long orderDetailsId, Integer paymentState) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("sum(amount)");
        cq.eq(true, "amountType", AmountTypeEnum.Settle.getCode());
        cq.eq(true, "orderDetailsId", orderDetailsId);
        if (FlymeUtils.isNotEmpty(paymentState)) {
            cq.eq(true, "paymentState", paymentState);
        }
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        return FlymeUtils.getBigDecimal(amount, new BigDecimal("0"));
    }


    @Override
    public BigDecimal totalSettleAmount(String settleApplyId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("sum(amount)");
        cq.eq(true, "parentId", settleApplyId);
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        return FlymeUtils.getBigDecimal(amount, new BigDecimal("0"));
    }


    @Override
    public BigDecimal totalAmount(String selectIds) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("sum(amount)");
        cq.in(true, "paymentId", selectIds.split(","));
        cq.isNull("invoiceId");
        BigDecimal amount = getObj(cq, e -> new BigDecimal(e.toString()));
        return FlymeUtils.getBigDecimal(amount, new BigDecimal("0"));
    }


    @Override
    public Integer countInvoiceNum(String settleApplyId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("count(*)");
        cq.eq(true, "parentId", settleApplyId);
        cq.isNull("invoiceNo");
        return getObj(cq, e -> Integer.parseInt(e.toString()));
    }

    @Override
    public Integer countInvoicePayNum(String settleApplyId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("count(*)");
        cq.eq(true, "parentId", settleApplyId);
        cq.isNull("payDate");
        return getObj(cq, e -> Integer.parseInt(e.toString()));
    }


    @Override
    public BusPayment getByOrderDetailsIdAndAmountType(String orderDetailsId, AmountTypeEnum amountType) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "orderDetailsId", orderDetailsId);
        cq.eq(true, "amountType", amountType.getCode());
        return getOne(cq, false);
    }

    /**
     * 已回款列表
     *
     * @param orderId
     * @return
     */
    @Override
    public List<EntityMap> getOrderReturnDetails(Long orderId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select(BusPayment.class, "paymentId", "orderDetailsId", "paymentState", "processInstanceId", "amountDate", "amount", "bankId", "remark");
        cq.eq(true, "payment.orderId", orderId);
        cq.eq("payment.amountType", AmountTypeEnum.CustomRefund.getCode());
        cq.orderByDesc("payment.createTime");
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            for (EntityMap map : list) {
                String processInstanceId = map.get("processInstanceId");
                Long orderDetailsId = map.getLong("orderDetailsId");
                EntityMap orderDetails = orderDetailsService.findById(orderDetailsId);
                if (FlymeUtils.isNotEmpty(orderDetails)) {
                    Long drugsId = orderDetails.getLong("drugsId");
                    BusDrugs drugs = drugsService.getById(drugsId);
                    if (FlymeUtils.isNotEmpty(drugs)) {
                        orderDetails.put("drugsName", drugs.getDrugsName());
                        orderDetails.put("drugsSpec", drugs.getDrugsSpec());
                    }
                    map.putAll(orderDetails);
                }
                if (FlymeUtils.isNotEmpty(processInstanceId)) {
                    //查询当前审批节点
                    Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).active().singleResult();
                    if (FlymeUtils.isNotEmpty(task)) {
                        map.put("taskName", task.getName());
                        map.put("taskId", task.getId());
                        map.put("taskDefinitionKey", task.getTaskDefinitionKey());
                    }
                }
                Long paymentId = map.getLong("paymentId");
                if (FlymeUtils.isNotEmpty(paymentId)) {
                    List<EntityMap> fileList = fileService.selectFileListByFileType(paymentId.toString(), BusPayment.class, "");
                    map.put("hkImage", fileList);

                    Long bankId = map.getLong("bankId");
                    SysBank bank = bankService.getById(bankId);
                    if (FlymeUtils.isNotEmpty(bank)) {
                        map.put("bankName", bank.getBankName());
                    }
                }
            }
        }
        return list;
    }


    /**
     * 两票添加市场保证金认款单
     *
     * @param busOrder
     * @param paymentState
     * @return
     */
    @Override
    public BusPayment addCustomBondPayment(BusOrder busOrder, Integer paymentState) {
        BusPayment payment = getByOrderIdAndAmountType(busOrder.getOrderId(), AmountTypeEnum.CustomBond);
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            payment.setPaymentNo("BJ" + busOrder.getOrderNo());
        }
        payment.setOrganizationId(busOrder.getOrganizationId());
        payment.setCompanyId(busOrder.getCompanyId());
        payment.setDeptId(busOrder.getDeptId());
        payment.setTitle("市场保证金认款单");
        payment.setAmount(busOrder.getTakeAmount());
        payment.setOrderId(busOrder.getOrderId().toString());
        payment.setAmountDate(busOrder.getTakeDate());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setCustomId(busOrder.getCustomId().toString());
        payment.setSupplierId(busOrder.getSupplierId());
        payment.setAmountType(AmountTypeEnum.CustomBond.getCode());
        payment.setBankId(busOrder.getBankId());
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        if (FlymeUtils.isNotEmpty(paymentState)) {
            payment.setPaymentState(paymentState);
        }
        saveOrUpdate(payment);
        return payment;
    }


    /**
     * 添加市场保证金认款单
     *
     * @param hyOrder
     * @return
     */
    @Override
    public BusPayment addCustomBondPayment(HyOrder hyOrder, HyBankItem bankItem) {
        String bankStatementId = bankItem.getBankStatementId();
        //收款账户ID
        Long bankId = bankItem.getBankId();
        SysBank bank = bankService.getById(bankId);
        ApiAssert.isNotEmpty("收款银行不存在", bank);
        BusPayment payment = getByOrderIdAndAmountType(hyOrder.getOrderId(), bankId, AmountTypeEnum.CustomBond);
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            Long paymentId = IdWorker.getId();
            payment.setPaymentId(paymentId);
            bankItem.setPaymentId(paymentId);
            payment.setPaymentNo(businessUtils.getPaymentNo(hyOrder.getCompanyId(), hyOrder.getUserId()));
        }
        payment.setOrganizationId(hyOrder.getOrganizationId());
        payment.setCompanyId(hyOrder.getCompanyId());
        payment.setDeptId(hyOrder.getDeptId());
        payment.setTitle("资保金认款单");
        payment.setRemitType(2);
        payment.setOrderId(hyOrder.getOrderId());
        payment.setAmountDate(hyOrder.getTakeDate());
        payment.setPrintTag(CommonConstants.DISABLED);
        //是否是提前认款
        payment.setAdvanceState(0);
        payment.setCustomId(hyOrder.getCustomId().toString());
        payment.setAmountType(AmountTypeEnum.CustomBond.getCode());
        payment.setBankName(bank.getBankName());
        payment.setBankNo(bank.getBankNo());
        payment.setBankId(bankId);
        payment.setAmount(bankItem.getTakeAmount());
        payment.setBankStatementId(bankStatementId);
        payment.setSurplusAmount(bankItem.getTakeAmount());
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_1);
        saveOrUpdate(payment);
        if (FlymeUtils.isNotEmpty(bankStatementId)) {
            BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
            payment.setPayBankNo(bankStatement.getBankNo());
            payment.setPayUserName(bankStatement.getCustomName());
            bankStatementService.updateBankStatement(bankStatementId, payment.getPaymentId(), CommonConstants.INT_1);
        }
        return payment;

    }


    /**
     * 添加保证金认款单
     *
     * @param salemanBalance
     * @return
     */
    @Override
    public BusPayment addSaleManBalancePayment(BusSalemanBalance salemanBalance) {
        BusPayment payment = getByOrderIdAndAmountType(salemanBalance.getSaleManBalanceId(), AmountTypeEnum.CustomBond);
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            payment.setPaymentNo(orderNoUtil.getCode("BJ"));
        }
        payment.setOrganizationId(salemanBalance.getOrganizationId());
        payment.setCompanyId(salemanBalance.getCompanyId());
        payment.setTitle("资保金认款单");
        BigDecimal depositAmount = FlymeUtils.getBigDecimal(salemanBalance.getDepositAmount(), "0");
        payment.setAmount(salemanBalance.getAmount().add(depositAmount));
        payment.setOrderId(salemanBalance.getSaleManBalanceId().toString());
        payment.setAmountDate(salemanBalance.getAmountDate());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setSaleManId(salemanBalance.getSaleManId());
        payment.setAmountType(AmountTypeEnum.CustomBond.getCode());
        payment.setDeptId(salemanBalance.getDeptId());
        Long bankId = salemanBalance.getBankId();
        SysBank bank = bankService.getById(bankId);
        if (FlymeUtils.isNotEmpty(bank)) {
            payment.setBankName(bank.getBankName());
            payment.setBankNo(bank.getBankNo());
        }
        payment.setBankId(bankId);
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
        saveOrUpdate(payment);
        return payment;
    }

    /**
     * 添加预付款认款单
     *
     * @param customBalance
     * @return
     */
    @Override
    public BusPayment addCustomBalancePayment(BusCustomBalance customBalance) {
        BusPayment payment = getByOrderIdAndAmountType(customBalance.getCustomBalanceId(), AmountTypeEnum.YfkAmount);
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            Long paymentId = IdWorker.getId();
            payment.setPaymentNo(paymentId.toString());
            payment.setPaymentId(paymentId);
        }
        payment.setTitle("客户预收款认款单");
        payment.setAmountType(AmountTypeEnum.YfkAmount.getCode());
        payment.setAmount(customBalance.getAmount());
        payment.setOrderId(customBalance.getCustomBalanceId().toString());
        payment.setAmountDate(customBalance.getAmountDate());
        payment.setOrganizationId(customBalance.getOrganizationId());
        payment.setCompanyId(customBalance.getCompanyId());
        payment.setCustomId(customBalance.getCustomId().toString());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
        //收款账户ID
        Long bankId = customBalance.getBankId();
        SysBank bank = bankService.getById(bankId);
        ApiAssert.isNotEmpty("收款银行不存在", bank);
        payment.setBankId(bankId);
        payment.setBankName(bank.getBankName());
        payment.setBankNo(bank.getBankNo());
        //付款账户信息
        Long payBankId = customBalance.getPayBankId();
        BusCustomBank customBank = customBankService.getById(payBankId);
        if (FlymeUtils.isNotEmpty(customBank)) {
            payment.setPayBankId(payBankId);
            payment.setPayBankName(customBank.getBankName());
            payment.setPayBankNo(customBank.getBankNo());
        }
        saveOrUpdate(payment);
        return payment;
    }


    /**
     * 添加全款认款单
     *
     * @param order
     * @param bankItem
     * @return
     */
    @Override
    public BusPayment addOrderPayment(HyOrder order, HyBankItem bankItem) {
        String bankStatementId = bankItem.getBankStatementId();
        //收款账户ID
        Long bankId = bankItem.getBankId();
        SysBank bank = bankService.getById(bankId);
        ApiAssert.isNotEmpty("收款银行不存在", bank);
        BusPayment payment = getByPaymentIdAndAmountType(bankItem.getPaymentId(), AmountTypeEnum.OrderAmount);
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            Long paymentId = IdWorker.getId();
            Long companyId = OpenHelper.getCompanyId();
            Long userId = OpenHelper.getUserId();
            String paymentNo = businessUtils.getPaymentNo(companyId, userId);
            payment.setPaymentNo(paymentNo);
            payment.setPaymentId(paymentId);
            bankItem.setPaymentId(paymentId);
        }
        payment.setTitle("客户全款认款单");
        payment.setAmountType(AmountTypeEnum.OrderAmount.getCode());
        payment.setOrderId(order.getOrderId());
        payment.setAmountDate(order.getTakeDate());
        payment.setDeptId(order.getDeptId());
        payment.setSaleManId(order.getSaleManId());
        payment.setSendArea(order.getSendArea());
        payment.setRenDate(DateUtil.now());
        payment.setAdvanceState(0);
        payment.setBusinessArea(order.getBusinessArea());
        payment.setRemitType(2);
        payment.setOrganizationId(order.getOrganizationId());
        payment.setCompanyId(order.getCompanyId());
        payment.setCustomId(order.getCustomId().toString());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setUserId(order.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_1);
        payment.setAmount(bankItem.getTakeAmount());
        payment.setSurplusAmount(bankItem.getTakeAmount());
        payment.setBankId(bankId);
        payment.setBankStatementId(bankStatementId);
        payment.setBankName(bank.getBankName());
        payment.setBankNo(bank.getBankNo());
        Long deptId = order.getDeptId();
        if (FlymeUtils.isNotEmpty(deptId)) {
            payment.setDeptId(deptId);
            BusDept dept = deptService.getById(deptId);
            payment.setDeptName(dept.getDeptName());
        }

        if (FlymeUtils.isNotEmpty(bankStatementId)) {
            BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
            payment.setPayBankNo(bankStatement.getBankNo());
            payment.setPayUserName(bankStatement.getCustomName());
            bankStatementService.updateBankStatement(bankStatementId, payment.getPaymentId(), CommonConstants.INT_1);
        }
        saveOrUpdate(payment);
        return payment;
    }

    /**
     * 添加预付款认款单
     *
     * @param deposit
     * @return
     */
    @Override
    public BusPayment addBusDepositPayment(BusDeposit deposit) {
        BusPayment payment = getById(deposit.getDepositId());
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            payment.setPaymentId(deposit.getDepositId());
            payment.setPaymentNo(deposit.getDepositId().toString());
        }
        payment.setOrganizationId(deposit.getOrganizationId());
        payment.setCompanyId(deposit.getCompanyId());
        payment.setTitle("保证金认款单");
        payment.setAmount(deposit.getPayAmount());
        payment.setOrderId(deposit.getDepositId().toString());
        payment.setAmountDate(deposit.getPayDate());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setSaleManId(deposit.getSaleManId());
        if (FlymeUtils.isNotEmpty(deposit.getCustomId())) {
            payment.setCustomId(deposit.getCustomId().toString());
        }
        payment.setAmountType(AmountTypeEnum.DepositAmount.getCode());
        Long bankId = deposit.getBankId();
        payment.setBankId(bankId);
        SysBank bank = bankService.getById(bankId);
        payment.setBankName(bank.getBankName());
        payment.setBankNo(bank.getBankNo());
        payment.setDeptId(deposit.getDeptId());
        payment.setAdvanceState(1);
        payment.setUserId(OpenHelper.getUserId());
        payment.setPaymentNo(deposit.getDepositNo());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
        saveOrUpdate(payment);
        return payment;
    }


    /**
     * 添加市场保证金认款单
     *
     * @param consumption
     * @return
     */
    @Override
    public BusPayment addConsumPayment(BusConsumption consumption) {
        BusPayment payment = getById(consumption.getConsumptionId());
        if (FlymeUtils.isEmpty(payment)) {
            payment = new BusPayment();
            payment.setPaymentId(consumption.getConsumptionId());
        }
        Long typeId = consumption.getPaymentTypeId();
        BusPaymenttype busPaymenttype = paymenttypeService.getById(typeId);
        payment.setOrganizationId(consumption.getOrganizationId());
        payment.setCompanyId(consumption.getCompanyId());
        payment.setDeptId(consumption.getDeptId());
        payment.setPrintTag(CommonConstants.DISABLED);
        payment.setTitle("日常费用-" + busPaymenttype.getPaymentTypeName());
        payment.setAmount(consumption.getApplyAmount());
        payment.setAmountType(busPaymenttype.getPaymentTypeCode());
        payment.setPaymentNo(consumption.getConsumptionNo());
        payment.setUserId(OpenHelper.getUserId());
        payment.setNickName(OpenHelper.getNickName());
        payment.setPaymentState(CommonConstants.INT_0);
        payment.setRemark(consumption.getRemark());
        saveOrUpdate(payment);
        return payment;

    }

    /**
     * 添加市场保证金认款单
     *
     * @param busOrder
     * @return
     */
    @Override
    public ResultBody addCustomBondPayment(BusOrder busOrder) {
        BusPayment payment = addCustomBondPayment(busOrder, CommonConstants.INT_0);
        return ResultBody.ok();
    }


    /**
     * 删除审批单
     *
     * @return
     */
    @Override
    public ResultBody deleteByAmountType(AmountTypeEnum amountType, Long orderDetailsId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq(true, "orderDetailsId", orderDetailsId);
        cd.eq(true, "amountType", amountType.getCode());
        remove(cd);
        return ResultBody.ok();
    }

    /**
     * 删除审批单
     *
     * @return
     */
    @Override
    public ResultBody deleteByParentId(Serializable parentId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq(true, "parentId", parentId);
        remove(cd);
        return ResultBody.ok();
    }


    /**
     * 删除审批单
     *
     * @return
     */
    @Override
    public ResultBody deleteOrderPayment(Serializable orderId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq(true, "orderId", orderId);
        cd.in("amountType", AmountTypeEnum.CustomBond.getCode(), AmountTypeEnum.OrderAmount.getCode());
        cd.eq(true, "advanceState", 0);
        remove(cd);
        return ResultBody.ok();
    }

    @Override
    public Boolean updatePaymentState(Serializable paymentId, String processInstanceId, Integer paymentState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "paymentState", paymentState);
        cu.set(true, "processInstanceId", processInstanceId);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean updatePaymentState(Long paymentId, Integer paymentState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "paymentState", paymentState);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean bindOrder(Long paymentId, String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "orderId", orderId);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean unBindOrder(Long paymentId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "orderId", null);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }


    @Override
    public Boolean updatePaymentState(String orderId, Integer paymentState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "paymentState", paymentState);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updatePaymentState(Long paymentId, Integer paymentState, Long payUserId, String payDate) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "paymentState", paymentState);
        cu.set(true, "payUserId", payUserId);
        cu.set(true, "payDate", payDate);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean updatePrintTag(Long paymentId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "printTag=printTag+1");
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean clearProcessInstanceId(String processInstanceId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "processInstanceId", "");
        cu.set(true, "paymentState", CommonConstants.INT_0);
        cu.eq(true, "processInstanceId", processInstanceId);
        return update(cu);
    }

    /**
     * 获取订单打印信息
     *
     * @param paymentId
     * @return
     */
    @Override
    public ResultBody getPrintInfo(Long paymentId, AmountTypeEnum amountType) {
        EntityMap paymentMap = findById(paymentId);
        Long deptId = paymentMap.getLong("deptId");
        Long bankId = paymentMap.getLong("bankId");
        String processInstanceId = paymentMap.get("processInstanceId");
        Long supplierId = paymentMap.getLong("supplierId");
        BusDept dept = deptService.getById(deptId);
        BaseUser user = userService.getById(paymentMap.getLong("userId"));
        if (FlymeUtils.isNotEmpty(dept)) {
            paymentMap.put("deptName", dept.getDeptName());
        }
        if (FlymeUtils.isNotEmpty(user)) {
            paymentMap.put("nickName", user.getNickName());
        }
        Long companyId = paymentMap.getLong("companyId");
        SysCompany company = companyService.getById(companyId);
        paymentMap.put("companyName", company.getCompanyName());
        String unitName = "";
        String bankName = "";
        String bankNo = "";
        String linkMan = "";
        if (companyId.equals(1L)) {
            paymentMap.put("testTitle", "复核员");
        }
        if (companyId.equals(4L)) {
            paymentMap.put("testTitle", "部门经理");
        }
        if (FlymeUtils.isNotEmpty(supplierId)) {
            BusSupplier supplier = supplierService.getById(supplierId);
            if (FlymeUtils.isNotEmpty(supplier)) {
                unitName = supplier.getSupplierName();
                paymentMap.put("taxNumber", supplier.getTaxNumber());
                paymentMap.put("supplierAddress", supplier.getAddress());
                paymentMap.put("linkTel", supplier.getLinkTel());
                linkMan = supplier.getLinkMan();
            }
        }
        //垫付款
        if (AmountTypeEnum.SupplierBond.equals(amountType)) {
            BusSupplierBank supplierBank = supplierBankService.getById(bankId);
            bankName = supplierBank.getBankName();
            bankNo = supplierBank.getBankNo();
            linkMan = supplierBank.getLinkMan();
        }
        //开票税金
        if (AmountTypeEnum.Invoice.equals(amountType)) {
            Long invoiceUnitId = paymentMap.getLong("invoiceUnitId");
            Integer invoiceType = paymentMap.getInt("invoiceType", 1);
            BusInvoiceunit invoiceUnit = invoiceunitService.getById(invoiceUnitId);
            unitName = invoiceUnit.getInvoiceunitName();
            BusInvoiceunitBank invoiceunitBank = invoiceunitBankService.getById(bankId);
            if (FlymeUtils.isNotEmpty(invoiceunitBank)) {

                bankName = invoiceunitBank.getBankName();
                bankNo = invoiceunitBank.getBankNo();
                linkMan = invoiceunitBank.getLinkMan();
            }
            if (invoiceType.equals(1)) {
                paymentMap.put("invoiceType", "专票");
            } else {
                paymentMap.put("invoiceType", "普票");
            }
        }
        //市场结算,退保证金
        if (AmountTypeEnum.Settle.equals(amountType) || AmountTypeEnum.CbReturn.equals(amountType)) {
            //查询收款单位
            Long saleManId = dept.getSalemanId();
            BusSaleman saleman = salemanService.getById(saleManId);
            if (FlymeUtils.isNotEmpty(saleman)) {
                unitName = saleman.getSaleManName();
            }
            BusSalemanBank salemanBank = salemanBankService.getById(bankId);
            bankName = salemanBank.getBankName();
            bankNo = salemanBank.getBankNo();
            BusSaleman jiesuan = salemanService.getById(salemanBank.getSaleManId());
            if (FlymeUtils.isNotEmpty(jiesuan)) {
                //收款人
                linkMan = salemanBank.getSaleManName();
            }
        }
        //日常费用
        if (AmountTypeEnum.Other.equals(amountType)) {
            BusConsumption consumption = consumptionService.getById(paymentId);
            if (FlymeUtils.isNotEmpty(consumption)) {
                unitName = consumption.getReceivingUnit();
                bankNo = consumption.getBankNo();
                linkMan = consumption.getReceivingUnit();
                bankName = consumption.getBank();
            }
        }
        //查询审批人
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    String message = comment.getFullMessage();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    if (roleCodes.contains("ROLE_NQBZ") || roleCodes.contains("ROLE_NQBZ_LD")) {
                        paymentMap.put("nickName_nqbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CGBZ") || roleCodes.contains("ROLE_CGBZ_LD")) {
                        paymentMap.put("nickName_nqbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CWBZ") || roleCodes.contains("ROLE_CWBZ_LD")) {
                        paymentMap.put("nickName_cwbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_ZJL") || roleCodes.contains("ROLE_ZJL_LD")) {
                        paymentMap.put("nickName_zjl", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_KJ") || roleCodes.contains("ROLE_KJ_LD")) {
                        paymentMap.put("nickName_kj", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_FHY")) {
                        paymentMap.put("nickName_nqbz", baseUser.getNickName());
                    }
                    if (FlymeUtils.isNotEmpty(message) && message.indexOf("#_#") != -1) {
                        String[] msg = message.split("#_#");
                        String taskKey = msg[2];
                        String nickName = msg[1];
                        if ("task_zjl".equals(taskKey)) {
                            paymentMap.put("nickName_zjl", nickName);
                        }
                    }

                }
            }
        }
        paymentMap.put("unitName", unitName);
        paymentMap.put("bankName", bankName);
        paymentMap.put("bankNo", bankNo);
        paymentMap.put("linkMan", linkMan);
        paymentMap.put("createTime", DateUtils.formatDate(paymentMap.get("createTime"), "yyyy-MM-dd"));
        return ResultBody.ok(paymentMap);
    }


    /**
     * 获取开票单打印信息
     *
     * @param inoviceId
     * @return
     */
    @Override
    public ResultBody getInvoicePrintInfo(Long inoviceId) {
        EntityMap result = new EntityMap();
        BusHyorderInovice hyorderInovice = hyorderInoviceService.getById(inoviceId);
        Long userId = hyorderInovice.getUserId();
        BaseUser user = userService.getById(userId);
        if (FlymeUtils.isNotEmpty(user)) {
            result.put("nickName", user.getNickName());
        }
        Long companyId = hyorderInovice.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        result.put("companyName", company.getCompanyName());
        String unitName = "";
        String bankName = company.getBankName();
        String bankNo = company.getBankNo();
        String linkTel = company.getLinkTel();
        String address = company.getCompanyAddress();
        String businessLicNo = company.getBusinessLicNo();
        Long invoiceUnitId = hyorderInovice.getInvoiceUnitId();
        Integer invoiceType = hyorderInovice.getInvoiceType();
        BusInvoiceunit invoiceUnit = invoiceunitService.getById(invoiceUnitId);
        unitName = invoiceUnit.getInvoiceunitName();
        if (invoiceType.equals(2)) {
            result.put("invoiceType", "专票");
        } else {
            result.put("invoiceType", "普票");
        }
        String drugsName = orderInoviceDetailsService.getDrugsNames(inoviceId);
        result.put("unitName", unitName);
        result.put("drugsName", drugsName);
        result.put("bankName", bankName);
        result.put("bankNo", bankNo);
        result.put("linkTel", linkTel);
        result.put("address", address);
        result.put("invoiceAmount", hyorderInovice.getInvoiceAmount());
        result.put("title", hyorderInovice.getTitle());
        result.put("noTaxAmount", hyorderInovice.getNoTaxAmount());
        result.put("secondTaxAmount", hyorderInovice.getSecondTaxAmount());
        result.put("taxAmount", hyorderInovice.getTaxAmount());
        result.put("senondInvoiceAmount", hyorderInovice.getSenondInvoiceAmount());
        result.put("businessLicNo", businessLicNo);
        result.put("createTime", DateUtils.formatDate(hyorderInovice.getInvoiceDate()));
        return ResultBody.ok(result);
    }

    /**
     * 获取订单打印信息
     *
     * @param paymentId
     * @return
     */
    @Override
    public ResultBody getHyPrintInfo(Long paymentId) {
        EntityMap paymentMap = findById(paymentId);
        String amountType = paymentMap.get("amountType");
        //收款方
        String payeeName = paymentMap.get("payeeName");
        Long deptId = paymentMap.getLong("deptId");
        Long bankId = paymentMap.getLong("bankId");
        String processInstanceId = paymentMap.get("processInstanceId");
        Long customId = paymentMap.getLong("customId");
        Long saleManId = paymentMap.getLong("saleManId");
        BusDept dept = deptService.getById(deptId);
        BaseUser user = userService.getById(paymentMap.getLong("userId"));
        if (FlymeUtils.isNotEmpty(dept)) {
            paymentMap.put("deptName", dept.getDeptName());
        }
        if (FlymeUtils.isNotEmpty(user)) {
            paymentMap.put("nickName", user.getNickName());
        }
        Long companyId = paymentMap.getLong("companyId");
        SysCompany company = companyService.getById(companyId);
        paymentMap.put("companyName", company.getCompanyName());
        //业务编码
        String businessNo = "";
        BusSaleman saleman = salemanService.getById(saleManId);
        if (FlymeUtils.isNotEmpty(saleman)) {
            businessNo = saleman.getSaleManBusinessNo();
        }
        Long parentId = null;
        if (amountType.equals(AmountTypeEnum.Invoice.getCode())) {
            BigDecimal amount = paymentMap.getBigDecimal("invoiceAmount");
            //支付金额
            paymentMap.put("amount", amount);
            paymentMap.put("nickName", OpenHelper.getNickName());
            parentId = paymentMap.getLong("parentId");
        }
        if (amountType.equals(AmountTypeEnum.Settle.getCode())) {
            BigDecimal amount = paymentMap.getBigDecimal("invoiceAmount");
            //支付金额
            paymentMap.put("amount", amount);
            paymentMap.put("nickName", OpenHelper.getNickName());
            Long invoicePaymentId = paymentMap.getLong("parentId");
            BusPayment invoicePayment = getById(invoicePaymentId);
            if (FlymeUtils.isNotEmpty(invoicePayment)) {
                BusPayment applyPayment = getById(invoicePayment.getParentId());
                parentId = applyPayment.getPaymentId();
            }
        }
        BusPayment payment = getById(parentId);
        if (FlymeUtils.isNotEmpty(payment)) {
            processInstanceId = payment.getProcessInstanceId();
        }
        //查询审批人
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    String message = comment.getFullMessage();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    if (roleCodes.contains("ROLE_XS_FHY")) {
                        paymentMap.put("nickName_xsfhy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_JSY")) {
                        paymentMap.put("nickName_jsy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_SW_FHY")) {
                        paymentMap.put("nickName_swfhy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_SW_SCZZ")) {
                        paymentMap.put("nickName_swsczz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_FHY")) {
                        paymentMap.put("nickName_fhy", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_JSBX")) {
                        paymentMap.put("nickName_jsbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_CWBZ")) {
                        paymentMap.put("nickName_cwbz", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_CW_ZJ")) {
                        paymentMap.put("nickName_cwzj", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_FLP_ZJL")) {
                        paymentMap.put("nickName_zjl", baseUser.getNickName());
                    }
                    if (roleCodes.contains("ROLE_HZ_CN") || roleCodes.contains("ROLE_FLP_CN")) {
                        paymentMap.put("nickName_cn", baseUser.getNickName());
                    }
                    if (FlymeUtils.isNotEmpty(message) && message.indexOf("#_#") != -1) {
                        String[] msg = message.split("#_#");
                        String taskKey = msg[2];
                        String nickName = msg[1];
                        if ("task_zjl".equals(taskKey)) {
                            paymentMap.put("nickName_zjl", nickName);
                        }
                    }

                }
            }
        }
        paymentMap.put("payeeName", payeeName);
        paymentMap.put("businessNo", businessNo);
        paymentMap.put("createTime", DateUtils.getNowDateTime());
        return ResultBody.ok(paymentMap);
    }

    @Override
    public ResultBody getRenkuanInfo(String paymentId) {
        ApiAssert.isNotEmpty("请选择打印单据", paymentId);
        List<EntityMap> orderDetails = new ArrayList<>();
        EntityMap result = new EntityMap();
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.in(true, "paymentId", paymentId.split(","));
        List<BusPayment> paymentList = list(cq);
        BusPayment firstPayment = paymentList.get(0);
        String amountType = firstPayment.getAmountType();
        //业务员ID
        Long saleManId = firstPayment.getSaleManId();
        //查询业务员
        BusSaleman saleman = salemanService.getById(saleManId);
        String saleManName = "";
        if (FlymeUtils.isNotEmpty(saleman)) {
            String businessArea = FlymeUtils.getString(firstPayment.getBusinessArea(), saleman.getAreaShortName());
            result.put("businessArea", businessArea);
            result.put("businessCode", saleman.getSaleManBusinessNo());
            saleManName = saleman.getSaleManName();
        }
        String customId = firstPayment.getCustomId();
        //获取客户
        BusCustom custom = busCustomService.getById(customId);
        if (FlymeUtils.isNotEmpty(custom)) {
            result.put("customName", custom.getCustomName());
        }
        result.put("saleManName", saleManName);
        String payUserName = firstPayment.getPayUserName();
        String subTitle = "认款单";
        if (AmountTypeEnum.OrderAmount.getCode().equals(amountType)) {
            subTitle = "现款认款单";
            if (FlymeUtils.isEmpty(payUserName)) {
                payUserName = custom.getCustomName();
            }
        }
        if (AmountTypeEnum.YfkAmount.getCode().equals(amountType)) {
            subTitle = "预收款认款单";
            payUserName = custom.getCustomName();
        }
        if (AmountTypeEnum.CustomBond.getCode().equals(amountType)) {
            subTitle = "资保金认款单";
            payUserName = saleManName;
        }
        if (AmountTypeEnum.DepositAmount.getCode().equals(amountType)) {
            subTitle = "保证金认款单";
            payUserName = saleManName;
        }
        result.put("subTitle", subTitle);
        Long companyId = firstPayment.getCompanyId();
        if (FlymeUtils.isNotEmpty(companyId)) {
            SysCompany company = companyService.getById(companyId);
            result.put("companyName", company.getCompanyName());
        }
        Long deptId = firstPayment.getDeptId();
        String deptType = DeptTypeEnum.ZY.getCode();
        if (FlymeUtils.isNotEmpty(deptId)) {
            BusDept dept = deptService.getById(deptId);
            deptType = dept.getDeptType();
            result.put("deptName", dept.getDeptName());
        }
        result.put("paymentNo", firstPayment.getPaymentNo());
        BigDecimal totalAmount = new BigDecimal("0");
        for (BusPayment payment : paymentList) {
            EntityMap item = new EntityMap();
            Integer remitType = FlymeUtils.getInteger(payment.getRemitType(), 1);
            BigDecimal amount = payment.getAmount();
            item.put("paymentNo", payment.getPaymentNo());
            item.put("amount", amount);
            item.put("amountDate", DateUtils.formatDate(payment.getAmountDate()));
            item.put("bankName", payment.getBankName());
            item.put("remitType", remitType.equals(3) ? "承兑" : "电汇");
            totalAmount = totalAmount.add(amount);
            String bankStatementId = payment.getBankStatementId();
            if (FlymeUtils.isNotEmpty(bankStatementId)) {
                BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
                if (FlymeUtils.isNotEmpty(bankStatement.getCustomName())) {
                    payUserName = bankStatement.getCustomName();
                }
            }
            item.put("payUserName", payUserName);
            orderDetails.add(item);
        }
        result.put("payUserName", payUserName);
        result.put("totalAmount", totalAmount);
        result.put("printTag", firstPayment.getPrintTag());
        result.put("sendArea", firstPayment.getSendArea());
        result.put("amountDate", DateUtils.formatDate(firstPayment.getCreateTime()));
        BaseUser user = userService.getById(firstPayment.getUserId());
        result.put("nickName", user.getNickName());
        String processInstanceId = firstPayment.getProcessInstanceId();
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            //查询审批人
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    String nickName = baseUser.getNickName();
                    //销售复核员
                    if (roleCodes.contains("ROLE_XS_FHY")) {
                        result.put("nickName_xsfhy", nickName);
                    }
                    //财务结算员
                    if (roleCodes.contains("ROLE_CW_JSY")) {
                        result.put("nickName_cwjsy", nickName);
                    }
                    //财务复核员
                    if (roleCodes.contains("ROLE_CW_FHY")) {
                        result.put("nickName_cwfhy", nickName);
                    }
                }
            }
        }
        result.put("orderDetails", orderDetails);
        result.put("createTime", DateUtils.getDateTime());
        return ResultBody.ok(result);
    }

    @Override
    public ResultBody getHuikuanInfo(Long paymentId) {
        ApiAssert.isNotEmpty("请选择打印单据", paymentId);
        List<EntityMap> orderDetails = new ArrayList<>();
        EntityMap result = new EntityMap();

        BusPayment payment = getById(paymentId);
        String amountType = payment.getAmountType();
        String businessArea = payment.getBusinessArea();
        //业务员ID
        Long saleManId = payment.getSaleManId();
        //查询业务员
        BusSaleman saleman = salemanService.getById(saleManId);
        String saleManName = "";
        if (FlymeUtils.isNotEmpty(saleman)) {
            result.put("businessArea", payment.getBusinessArea());
            result.put("businessCode", saleman.getSaleManBusinessNo());
            saleManName = saleman.getSaleManName();
        }
        String customId = payment.getCustomId();
        //获取客户
        BusCustom custom = busCustomService.getById(customId);
        if (FlymeUtils.isNotEmpty(custom)) {
            result.put("customName", custom.getCustomName());
        }
        result.put("saleManName", saleManName);
        String payUserName = payment.getPayUserName();
        String subTitle = "回款认款单";
        Long parentId = payment.getParentId();
        if (FlymeUtils.isNotEmpty(parentId)) {
            subTitle = "回款单";
        }
        result.put("subTitle", subTitle);
        Long companyId = payment.getCompanyId();
        if (FlymeUtils.isNotEmpty(companyId)) {
            SysCompany company = companyService.getById(companyId);
            result.put("companyName", company.getCompanyName());
        }
        Long deptId = payment.getDeptId();
        String deptType = DeptTypeEnum.ZY.getCode();
        if (FlymeUtils.isNotEmpty(deptId)) {
            BusDept dept = deptService.getById(deptId);
            deptType = dept.getDeptType();
            result.put("deptName", dept.getDeptName());
        }
        result.put("paymentNo", payment.getPaymentNo());
        List<EntityMap> orderDetailsList = hyorderReturnService.selectByReturnId(paymentId);
        result.put("payUserName", payUserName);
        result.put("totalAmount", payment.getAmount());
        result.put("printTag", payment.getPrintTag());
        result.put("sendArea", payment.getSendArea());
        result.put("bankName", payment.getBankName());
        result.put("amountDate", DateUtils.formatDate(payment.getAmountDate()));
        result.put("printDate", DateUtils.formatDate(payment.getCreateTime()));
        BaseUser user = userService.getById(payment.getUserId());
        result.put("nickName", user.getNickName());
        String processInstanceId = payment.getProcessInstanceId();
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            //查询审批人
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    String nickName = baseUser.getNickName();
                    //销售复核员
                    if (roleCodes.contains("ROLE_XS_FHY")) {
                        result.put("nickName_xsfhy", nickName);
                    }
                    //财务结算员
                    if (roleCodes.contains("ROLE_CW_JSY")) {
                        result.put("nickName_cwjsy", nickName);
                    }
                    //财务复核员
                    if (roleCodes.contains("ROLE_CW_FHY")) {
                        result.put("nickName_cwfhy", nickName);
                    }
                }
            }
        }
        result.put("orderDetails", orderDetailsList);
        result.put("createTime", DateUtils.getDateTime());
        return ResultBody.ok(result);
    }


    @Override
    public void afterGet(CriteriaQuery cq, EntityMap result) {
        Long paymentId = result.getLong("paymentId");
        Integer fileGroup = cq.getInt("fileGroup", null);
        if (FlymeUtils.isNotEmpty(paymentId)) {
            List<EntityMap> fileList = fileService.selectFileListByFileGroup(paymentId.toString(), "BusPayment", fileGroup);
            result.put("paymentImage", fileList);
        }
        Long deptId = result.getLong("deptId");
        if (FlymeUtils.isNotEmpty(deptId)) {
            BusDept dept = deptService.getById(deptId);
            if (FlymeUtils.isNotEmpty(dept)) {
                result.put("deptName", dept.getDeptName());
                result.put("deptType", dept.getDeptType());
            }
        }
        Long saleManId = result.getLong("saleManId");
        if (FlymeUtils.isNotEmpty(saleManId)) {
            BusSaleman saleMan = salemanService.getById(saleManId);
            if (FlymeUtils.isNotEmpty(saleMan)) {
                result.put("saleManName", saleMan.getSaleManName());
                result.put("multipleArea", saleMan.getMultipleArea());
            }
        }
        Long customId = result.getLong("customId");
        if (FlymeUtils.isNotEmpty(customId)) {
            BusCustom custom = busCustomService.getById(customId);
            if (FlymeUtils.isNotEmpty(custom)) {
                result.put("customName", custom.getCustomName());
            }
        }
        super.afterGet(cq, result);
    }

    @Override
    public ResultBody afterDelete(CriteriaDelete cd, Serializable[] ids) {
        EntityMap map = cd.getRequestMap();
        //流程实例ID
        String processInstanceId = map.get("processInstanceId");
        String bankStatementId = map.get("bankStatementId");
        if (FlymeUtils.isNotEmpty(bankStatementId)) {
            bankStatementService.clearPaymentId(bankStatementId);
        }
        //删除流程数据
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            processInstanceService.delete(processInstanceId, true, null, "删除");
        }
        return super.afterDelete(cd, ids);
    }

    @Override
    public EntityMap getInvoiceInfo(String settleIds) {
        EntityMap map = new EntityMap();
        BigDecimal totalSettleMap = totalAmount(settleIds);
        map.put("totalSettleAmount", totalSettleMap);
        return map;
    }

    @Override
    public ResultBody getRefundBondInfo(String selectIds) {
        EntityMap map = new EntityMap();
        EntityMap refundBondMap = hyOrderDetailService.totalRefundBondInfo(selectIds);
        Integer saleManIdCount = refundBondMap.getInt("saleManIdCount");
        if (saleManIdCount > 1) {
            return ResultBody.failed("存在多个结算人,请检查退款数据");
        }
        Long saleManId = refundBondMap.getLong("saleManId");
        if (FlymeUtils.isNotEmpty(saleManId)) {
            BusSaleman saleMan = salemanService.getById(saleManId);
            map.put("saleManName", saleMan.getSaleManName());
            map.put("saleManId", saleMan.getSaleManId());
        }
        BigDecimal customBondTakeAmount = refundBondMap.getBigDecimal("customBondTakeAmount");
        map.put("customBondTakeAmount", customBondTakeAmount);
        return ResultBody.ok(map);
    }

    @Override
    public ResultBody getReturnInfo(String selectIds) {
        EntityMap map = new EntityMap();
        EntityMap refundBondMap = hyorderReturnService.totalReturnAmountInfo(selectIds);
        Integer customIdCount = refundBondMap.getInt("customIdCount");
        if (customIdCount > 1) {
            return ResultBody.failed("所选数据存在多家单位,请重新选择");
        }
        Long customId = refundBondMap.get("customId");
        if (FlymeUtils.isNotEmpty(customId)) {
            BusCustom custom = busCustomService.getById(customId);
            map.put("customName", custom.getCustomName());
            map.put("customCode", custom.getCustomCode());
            map.put("customId", custom.getCustomId());
        }
        BigDecimal saleAmount = refundBondMap.getBigDecimal("saleAmount");
        map.put("saleAmount", saleAmount);
        return ResultBody.ok(map);
    }

    @Override
    public ResultBody getRefundHkInfo(String selectIds) {
        EntityMap map = new EntityMap();
        BusPayment payment = getById(selectIds);
        String amountType = payment.getAmountType();
        BigDecimal amount = payment.getSurplusAmount();
        map.put("payeeName", payment.getPayUserName());
        if (AmountTypeEnum.OrderAmount.getCode().equals(amountType)) {
            String customId = payment.getCustomId();
            if (FlymeUtils.isNotEmpty(customId)) {
                BusCustom custom = busCustomService.getById(customId);
                map.put("payeeName", custom.getCustomName());
                map.put("customId", customId);
            }
        }
        if (AmountTypeEnum.CustomBond.getCode().equals(amountType)) {
            Long saleManId = payment.getSaleManId();
            if (FlymeUtils.isNotEmpty(saleManId)) {
                map.put("payeeName", payment.getPayUserName());
                map.put("saleManId", saleManId);
            }
        }
        String bankStatementId = payment.getBankStatementId();
        BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
        if (FlymeUtils.isNotEmpty(bankStatement)) {
            map.put("bankNo", bankStatement.getBankNo());
        }
        map.put("amount", amount);
        map.put("amountType", amountType);

        return ResultBody.ok(map);
    }

    @Override
    public ResultBody getSettleApplyInfo(Integer settleType, String settleIds) {
        EntityMap map = new EntityMap();
        Integer saleManCount = 0;
        Long saleManId = null;
        Integer drugTypeCount = 0;
        BigDecimal totalSettleAmount = hyorderReturnService.totalSettleApplyAmount(settleIds, settleType);
        EntityMap saleMan = hyorderReturnService.countSettleManId(settleIds, settleType);
        if (FlymeUtils.isNotEmpty(saleMan)) {
            saleManCount = saleMan.getInt("count", 0);
            saleManId = saleMan.get("manId");
        }
        if (saleManCount > 1) {
            //return ResultBody.failed("存在多个结算人,请检查结算数据");
        }
        if (drugTypeCount > 1) {
            return ResultBody.failed("招商和自营商品不可同时申请");
        }
        if (FlymeUtils.lezero(totalSettleAmount)) {
            //return ResultBody.failed("结算金额必须大于0");
        }
        if (FlymeUtils.isEmpty(saleManId)) {
            //return ResultBody.failed("结算人不存在");
        }
        BusSaleman man = salemanService.getById(saleManId);
        if (FlymeUtils.isEmpty(man)) {
            //return ResultBody.failed("结算人不存在");
        }
        //map.put("saleManName", man.getSaleManName());
        map.put("totalSettleAmount", totalSettleAmount);
        //map.put("saleManId", saleManId);
        return ResultBody.ok(map);
    }

    @Override
    public ResultBody getDeptSettleApplyInfo(String settleIds) {
        EntityMap totalSettleAmount = hyorderReturnService.totalDeptSettleApplyAmount(settleIds);
        return ResultBody.ok(totalSettleAmount);
    }


    @Override
    public ResultBody getSettlePayInfo(String settleIds) {
        EntityMap map = new EntityMap();
        EntityMap totalSettleAmountMap = orderInoviceDetailsService.totalSettleAmount(settleIds);
        BigDecimal totalSettleAmount = totalSettleAmountMap.getBigDecimal("settleAmount");
        Integer saleManCount = totalSettleAmountMap.getInt("saleManIdCount", 0);
        String saleManId = totalSettleAmountMap.get("saleManId");
        String drugType = totalSettleAmountMap.get("drugType");
        Long settleApplyId = totalSettleAmountMap.getLong("settleApplyId");
        if (saleManCount > 1) {
            return ResultBody.failed("禁止申请多人结算");
        }
        if (FlymeUtils.lezero(totalSettleAmount)) {
            return ResultBody.failed("结算金额必须大于0");
        }
        BusSaleman man = salemanService.getById(saleManId);
        if (FlymeUtils.isEmpty(man)) {
            return ResultBody.failed("结算人不存在");
        }
        map.put("saleManName", man.getSaleManName());
        map.put("totalSettleAmount", totalSettleAmount);
        map.put("saleManId", saleManId);
        map.put("deptId", man.getDeptId());
        map.put("settleApplyId", settleApplyId);
        return ResultBody.ok(map);
    }


    @Override
    public List<EntityMap> getHyOrderReturnDetails(Long orderId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select(BusPayment.class, "paymentId", "orderDetailsId", "paymentState", "processInstanceId", "amountDate", "amount", "bankId", "remark");
        cq.eq(true, "payment.orderId", orderId);
        cq.eq("payment.amountType", AmountTypeEnum.CustomRefund.getCode());
        cq.orderByDesc("payment.createTime");
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            for (EntityMap map : list) {
                String processInstanceId = map.get("processInstanceId");
                Long orderDetailsId = map.getLong("orderDetailsId");
                EntityMap orderDetails = hyOrderDetailService.findById(orderDetailsId);
                if (FlymeUtils.isNotEmpty(orderDetails)) {
                    Long policyDrugId = orderDetails.getLong("policyDrugId");
                    BusPolicyDrug policyDrug = policyDrugService.getById(policyDrugId);
                    if (FlymeUtils.isNotEmpty(policyDrug)) {
                        orderDetails.put("drugsName", policyDrug.getDrugsName());
                        orderDetails.put("drugsSpec", policyDrug.getDrugsSpec());
                    }
                    map.putAll(orderDetails);
                }
                if (FlymeUtils.isNotEmpty(processInstanceId)) {
                    //查询当前审批节点
                    Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).active().singleResult();
                    if (FlymeUtils.isNotEmpty(task)) {
                        map.put("taskName", task.getName());
                        map.put("taskId", task.getId());
                        map.put("taskDefinitionKey", task.getTaskDefinitionKey());
                    }
                }
                Long paymentId = map.getLong("paymentId");
                if (FlymeUtils.isNotEmpty(paymentId)) {
                    List<EntityMap> fileList = fileService.selectFileListByFileType(paymentId.toString(), BusPayment.class, "");
                    map.put("hkImage", fileList);

                    Long bankId = map.getLong("bankId");
                    SysBank bank = bankService.getById(bankId);
                    if (FlymeUtils.isNotEmpty(bank)) {
                        map.put("bankName", bank.getBankName());
                    }
                }
            }
        }
        return list;
    }

    /**
     * 删除审批单
     *
     * @return
     */
    @Override
    public ResultBody removeByOrderId(AmountTypeEnum amountType, String orderId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq(true, "orderId", orderId);
        cd.eq(true, "amountType", amountType.getCode());
        remove(cd);
        return ResultBody.ok();
    }

    @Override
    public BusPayment getSettlePayment(Long invoiceId, Long saleManId) {
        CriteriaQuery cq = new CriteriaQuery(BusPayment.class);
        cq.eq(true, "parentId", invoiceId);
        cq.eq(true, "saleManId", saleManId);
        return getOne(cq, false);
    }

    @Override
    public Boolean clearInvoiceId(Serializable invoiceId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "invoiceId", null);
        cu.set(true, "invoiceUnitId", null);
        cu.eq(true, "invoiceId", invoiceId);
        return update(cu);
    }

    @Override
    public Boolean updateSurplusAmount(Long paymentId, BigDecimal surplusAmount) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "surplusAmount", surplusAmount);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public Boolean addSurplusAmount(Long paymentId, BigDecimal useAmount) {
        BusPayment busPayment = getById(paymentId);
        if (FlymeUtils.isNotEmpty(busPayment)) {
            BigDecimal surplusAmount = FlymeUtils.getBigDecimal(busPayment.getSurplusAmount(), "0");
            surplusAmount = surplusAmount.add(useAmount);
            busPayment.setSurplusAmount(surplusAmount);
            updateById(busPayment);
        }
        return true;
    }

    @Override
    public Boolean updateSaleAmount(Long paymentId, BigDecimal saleAmout) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "saleAmount", saleAmout);
        cu.eq(true, "paymentId", paymentId);
        return update(cu);
    }

    @Override
    public List<Long> selectByParentId(Long paymentId) {
        CriteriaQuery<BusPayment> cq = new CriteriaQuery(BusPayment.class);
        cq.select("paymentId");
        cq.nested(e -> e.eq(true, "paymentId", paymentId).or().eq(true, "parentId", paymentId));
        return listObjs(cq, e -> Long.parseLong(e.toString()));
    }

}
